package cn.ac.iie.di.ban.tools;

import cn.ac.iie.di.ban.handler.HttpSe2DBHandler;
import static cn.ac.iie.di.ban.se.server.Http2MetaDB.httpSe2DBHandlerSet;
import cn.ac.iie.di.commons.httpserver.framework.handler.HandlerI;
import cn.ac.iie.di.commons.httpserver.framework.server.HttpServer;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.eclipse.jetty.server.Request;

public class HttpHelper implements HandlerI {

    private static Logger logger = Logger.getLogger(HttpHelper.class.getName());
    private HttpServer hserver;
    private String strCheck = "";

    @Override
    public void init() {

        if ("".equals(strCheck)) {
            for (String entityName : httpSe2DBHandlerSet.keySet()) {
                strCheck += entityName;
            }
        }

    }

    public void getServer() {
        try {
            if (hserver != null) {
                return;
            }
            hserver = HttpServer.getHttpServer(HttpSe2DBHandler.getIp(), HttpSe2DBHandler.getPort(), HttpSe2DBHandler.getParallel());//"localhost"
            hserver.registerContext("/data");//注册对外暴露的服务
            hserver.registerContextHandler("/data", "/", HttpHelper.class);//注册服务对应的处理类。
            hserver.startup();//服务启动
            logger.info("http server start ok");
            logger.info(HttpSe2DBHandler.getIp() + " " + HttpSe2DBHandler.getPort() + " " + HttpSe2DBHandler.getParallel());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    @Override
    public void execute(Request rqst, HttpServletRequest hsr, HttpServletResponse hsr1) throws Exception {
        try {
            logger.info("receive one msg from https " + hsr.getRemoteAddr());
            if (HttpSe2DBHandler.isStoped) {
                Map<String, Object> result = new HashMap<>(2);
                result.put("status", "stopping");
                result.put("detail", "project is stopping ...");
                JSONObject jsonObject = JSONObject.fromObject(result);
                hsr1.getWriter().write(jsonObject.toString());//返回
                hsr1.setStatus(HttpServletResponse.SC_OK);//设置处理成功 
                return;
            }
            
            Map<String, Object> requestMsg = new HashMap<>(5);
            String scope = rqst.getParameter("scope");//获得参数
            String opration = rqst.getParameter("opration");//获得参数
            Boolean checkParamsAllow = scope == null || "".equals(scope) || !strCheck.contains(scope)
                    || opration == null || "".equals(opration) || !"new,update,search,del".contains(opration);
            if (checkParamsAllow) {
                Map<String, Object> result = new HashMap<>(2);
                result.put("status", "error");
                result.put("detail", "Are you kidding me? parameter error !! scope:" + scope + " opration:" + opration + " content:" + rqst.getParameter("content") + " condition" + rqst.getParameter("condition"));
                JSONObject jsonObject = JSONObject.fromObject(result);
                hsr1.getWriter().write(jsonObject.toString());//返回
                hsr1.setStatus(HttpServletResponse.SC_OK);//设置处理成功 
                logger.error("get parameter error scope:" + scope + " opration:" + opration + " content:" + rqst.getParameter("content") + " condition" + rqst.getParameter("condition"));
                return;
            }
            String content = rqst.getParameter("content");//获得参数
            String condition = rqst.getParameter("condition");//获得参数
            logger.debug("request is: "+scope);
            logger.debug("request is: "+opration);
            logger.debug("request is: "+content);
            logger.debug("request is: "+condition);
            if (content == null) {
                content = "";
            }
            if (condition == null) {
                condition = "";
            }
            requestMsg.put("scope", scope);
            requestMsg.put("opration", opration);
            requestMsg.put("content", content);
            requestMsg.put("condition", condition);
//        System.out.println("============"+requestMsg.toString());
            String rflag = System.nanoTime() + "";
            requestMsg.put("rflag", rflag);
            shuntMsg(requestMsg, scope);
            for (int i = 0;; i++) {
                Object result = HttpSe2DBHandler.result.remove(rflag);
                if (result == null) {
                    try {
                        Thread.sleep(i * 10);
                    } catch (Exception e) {
                    }
                    if (System.currentTimeMillis() % 200 == 0) {
                        logger.info("waitting for response..." + i);
                    }
                } else {
                    
                    hsr1.setHeader("content-type", "text/html;charset=UTF-8");
                    hsr1.setCharacterEncoding("UTF-8");
                    hsr1.getWriter().write(result.toString());//返回
                    hsr1.setStatus(HttpServletResponse.SC_OK);//设置处理成功
                    break;
                }
            }
        } catch (IOException ex) {
            logger.error(ex.getMessage(), ex);
        }

    }

    public void startServer() {
        try {
            hserver.startup();
        } catch (Exception ex) {

        }
    }

    public void shutServer() {
        try {
            hserver.shutdown();
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            try {
                hserver.shutdown();
            } catch (Exception e) {
            }
        } finally {
            hserver = null;
        }
    }

    /*
    分流
     */
    public void shuntMsg(Map<String, Object> msg, String scope) {
        for (String entityName : httpSe2DBHandlerSet.keySet()) {
            if (entityName.equals(scope)) {
                httpSe2DBHandlerSet.get(entityName).disposeMessages(msg);
            }
        }
    }
}
